﻿using System;
using System.Data;
using HSM.Business;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;
using Guru.Web.Controls.Telerik;
using Guru.Data;
using Telerik.Web.UI;
using System.Text.RegularExpressions;
using System.Web;


/// <summary>
/// Summary description for Common
/// </summary>
public static class HSMCommon
{ 
    #region XML
    public static string ConvertObjectToXML(object obj, Type type)
    {
        XmlSerializer ser = new XmlSerializer(type);
        using (MemoryStream memStream = new MemoryStream())
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = Encoding.UTF8;
            settings.Indent = false;
            settings.NewLineChars = string.Empty;
            settings.ConformanceLevel = ConformanceLevel.Document;
            using (XmlWriter xmlWriter = XmlTextWriter.Create(memStream, settings))
            {
                ser.Serialize(xmlWriter, obj);
                return Encoding.UTF8.GetString(memStream.ToArray());
            }
        }
    }
    /// <summary>
    /// Convert XML UTF8 string to object
    /// </summary>
    /// <param name="xml"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    /// @Author: HungDinh
    public static object ConvertXMLToObject(string xml, Type type)
    {
        XmlSerializer ser = new XmlSerializer(type);
        using (MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
            object obj = ser.Deserialize(memStream);
            return obj;
        }
    }

    #endregion

    #region Controls & GUI
    public static void BindComboBox(this GuruComboBox cbo, string type)
    {
        GuruParameterCollection parameters = new GuruParameterCollection();
        parameters.AddUserLoggedParams();
        parameters.Add("@Type", type, DbType.String);

        DataTable dtValues = HSMCommon.HSMBusiness.GetDataTable("spa_HSM_REF_GetDropDownValues", parameters);
        if (string.IsNullOrEmpty(cbo.DataTextField))
        {
            cbo.DataTextField = GetColumByLanguage(cbo.Page as HSMPage);
        }
        if (string.IsNullOrEmpty(cbo.DataValueField))
        {           
            cbo.DataValueField = "FixedID";          
        }
        else if (cbo.DataValueFields != null && cbo.DataValueFields.Length > 1)
        {
            HSMCommon.AddComboBoxItem(cbo,dtValues);
            return;
        }
        cbo.DataSource = dtValues;
        cbo.DataBind();
    }

    public static void BindComboBox(this GuruComboBox cbo, string type, bool addNullItem)
    {
        BindComboBox(cbo, type);
        if (addNullItem)
        {
            cbo.Items.Insert(0, new RadComboBoxItem(string.Empty, string.Empty));
        }
    }
    public static void SetComboValue(this GuruComboBox cbo, object val) 
    {
        string value = val.ToSafeString();
        if (string.IsNullOrEmpty(value)) cbo.SelectedIndex = -1;
        else if (cbo.FindItemIndexByValue(value.Trim()) != null)
        {
            cbo.SelectedValue = value;
        }
        else cbo.SelectedIndex = -1;
    }
    public static void SetDatePickerValue(this GuruDatePicker picker, object val)
    {
        if (val == null || val == DBNull.Value)
        {
            picker.SelectedDate = null;
        }
        else picker.SelectedDate = Convert.ToDateTime(val);
    }
    #endregion

    #region Utilities, extention methods
    public static string RemoveVietnamese(this string unicodeString)
    {
        if (string.IsNullOrEmpty(unicodeString))
            return string.Empty;
        //Remove VietNamese character      
        unicodeString = unicodeString.ToLower();
        unicodeString = Regex.Replace(unicodeString, "[áàảãạâấầẩẫậăắằẳẵặ]", "a");
        unicodeString = Regex.Replace(unicodeString, "[éèẻẽẹêếềểễệ]", "e");
        unicodeString = Regex.Replace(unicodeString, "[iíìỉĩị]", "i");
        unicodeString = Regex.Replace(unicodeString, "[óòỏõọơớờởỡợôốồổỗộ]", "o");
        unicodeString = Regex.Replace(unicodeString, "[úùủũụưứừửữự]", "u");
        unicodeString = Regex.Replace(unicodeString, "[yýỳỷỹỵ]", "y");
        unicodeString = Regex.Replace(unicodeString, "[đ]", "d");
        return unicodeString;
    }
    public static string GetColumByLanguage(HSMPage page)
    {
        return "Name" + page.CurrentLanguage;
    }
   
    public static void AddComboBoxItem(GuruComboBox cbo, DataTable dt)
    {
        cbo.Items.Clear();
        foreach (DataRow dr in dt.Rows)
        {            
            string vals = string.Empty;
            foreach (string s in cbo.DataValueFields)
            {
                if (!string.IsNullOrEmpty(s))
                {
                    vals += dr[s.Trim()].ToString() + cbo.ValueSeparator;
                }
            }
            GuruComboBoxItem item = new GuruComboBoxItem();
            item.Text = dr[cbo.DataTextField.Trim()].ToString();
            item.Value = vals.Trim(cbo.ValueSeparator);
            cbo.Items.Add(item);
        }
    }
    public static string GetFirstSelectedValue(this GuruComboBox cbo)
    {
        int sIndex = cbo.SelectedValue.IndexOf(cbo.ValueSeparator);
        if (sIndex <= 0) return cbo.SelectedValue;
        else return cbo.SelectedValue.Substring(0, sIndex);
    }
    public static string ToSafeString(this object val)
    {
        if (val == null || val == DBNull.Value)
            return string.Empty;
        else return val.ToString();
    
    }
    public static string ToSafeNumberString(this object val)
    {
        if (val == null || val == DBNull.Value)
            return "0";
        else return val.ToString();

    }
    public static double ToMoney(this object val)
    {
        return double.Parse(ToSafeNumberString(val));

    }
    public static bool IsNotNull(this object val)
    {
        if (val == null || val == DBNull.Value)
            return false;
        else return true;

    }
    public static bool IsNotEmpty(this object val)
    {
        if (val == null || val == DBNull.Value)
            return false;
        else if (string.IsNullOrEmpty(val.ToString().Trim()))
            return false;
        else return true;

    }
    public static string ValidateResponse(this object val)
    {
        if (val == null || val == DBNull.Value)
        {
            return string.Empty;
        }
        else
        {
            return System.Web.HttpUtility.HtmlEncode(val.ToString());
        }
    }
    public static string DecodeHTML(this string data)
    {
        return System.Web.HttpUtility.HtmlDecode(data);
    }

    public static int ToInt(this object val)
    {
        return Convert.ToInt32(val);
    }
    #endregion

    #region Database Parameters
    public static HSMBusiness HSMBusiness
    {
        get { return new HSMBusiness(HSMSessionManager.CurrentClientID); }
    }
    public static void AddUserLoggedParams(this GuruParameterCollection parameters)
    {
        parameters.Add("@ClientID", HSMSessionManager.CurrentClientID, DbType.Int32);
        parameters.Add("@HotelID", HSMSessionManager.CurrentHotelID, DbType.Int32);
        parameters.Add("@UserID", HSMSessionManager.CurrentUser.UserID, DbType.Guid);       
    }
    #endregion

    public static string UrlHSM
    {
        get { return HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.AbsolutePath, string.Empty) + HttpContext.Current.Request.ApplicationPath; }
    }

    public static DataTable GetRefAppConfig()
    {
        GuruParameterCollection parameters = new GuruParameterCollection();
        parameters.Add("@ClientID", HSMSessionManager.CurrentClientID, DbType.Int32);
        return HSMCommon.HSMBusiness.GetDataTable("spa_REF_AppConfigs_Get", parameters);
    }

    public static string ReadTemplate(string filePath)
    {
        StreamReader templateFile = new StreamReader(HttpContext.Current.Server.MapPath(filePath));
        string content = templateFile.ReadToEnd();
        templateFile.Close();
        return content;
    }

}
